<?php
/**
 * Copyright (c) 2006-2007, Julien PORTALIER
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright    Copyright (c) 2006-2007, Julien PORTALIER
 * @link         http://featherphp.googlecode.com/
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

require_once APP.'config'.DS.'locales.php';

/**
 * Configures Locale.
 */
class LocaleComponent extends Locales
{
	public $lang;
	
	function startup(Controller $ctrl)
	{
		# timezone
		$tz = $ctrl->Session->check('User.timezone') ?
			$ctrl->Session->read('User.timezone') : Core::locale_timezone;
		date_default_timezone_set($tz);
		
		# language
		/*
		if (isset($ctrl->params['lang']))
			$lang = $ctrl->params['lang'];
		if (empty($lang) and $ctrl->Session->check('User.lang'))
			$lang = $ctrl->Session->read('User.lang');
		if (empty($lang))
			$lang = $this->autodetect();
		$this->set($lang);
		*/
		$this->set(Core::locale_default);
	}
	
	function set($lang)
	{
		$this->lang = empty($this->locales[$lang]) ? Core::locale_default : $lang;
		
		// locale
		putenv("LANG=".$this->locales[$this->lang]);
		setlocale(LC_ALL, $this->locales[$this->lang].'.'.Core::charset);
		setlocale(LC_NUMERIC, 'C');
		
		// translation (gettext)
		bindtextdomain('messages', APP.'locale'.DS); 
		textdomain('messages');
	}
	
	function get()
	{
		return $this->locales[$this->lang];
	}
	
	function autodetect()
	{
		$accepts = env('HTTP_ACCEPT_LANGUAGE');
		$accepts = explode(',', $accepts);
		
		foreach($accepts as $lang)
		{
			$pos = strpos($lang, ';q=');
			if ($pos)
				$lang = substr($lang, 0, $pos);
			if (isset($this->locales[$lang]))
				return $lang;
		}
		return null;
	}
}
?>